package com.example.lishop.service.impl

import com.example.lishop.entity.BUserEntity
import com.example.lishop.exception.ExceptEnum
import com.example.lishop.repository.UserRepository
import com.example.lishop.service.UserService
import com.example.lishop.util.SnowflakeUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import org.springframework.util.Assert

/**
 * Created on 2021/3/14 18:14
 * @author shuguo
 */
@Service
class UserServiceImpl : UserService {

    @Autowired
    lateinit var repository: UserRepository

    override fun add(data: BUserEntity): BUserEntity {
        data.userId = ""+ SnowflakeUtil.instance.nextId(6)
        return repository.save(data)
    }

    override fun update(data: BUserEntity) {
        detail(data)
        return repository.update(data)
    }

    override fun del(bean:BUserEntity) {
        detail(bean)
        repository.del(bean.userId)
    }

    override fun list(page:Int, size:Int): Page<BUserEntity> {
        val req: Pageable = PageRequest.of(page, size)
        return repository.findAll(req)
    }

    override fun detail(bean:BUserEntity): BUserEntity? {
        val data = repository.findByUserId(bean.userId)
        Assert.notNull(data, ExceptEnum.NOT_EXIST)
        return data
    }

    override fun detailByPhone(bean: BUserEntity): BUserEntity? {
        val item = repository.findByPhone(bean.phone)
        Assert.notNull(item, ExceptEnum.USER_NOT_EXIST)
        Assert.isTrue(bean.pwd == item?.pwd, ExceptEnum.USER_PWD_ERROR)
        return item
    }

}